<template>
  <el-form :model="params" class="demo-form-inline" ref="params" :rules="rules" label-position="top">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item :label="$t('auth.menu.pre')" prop="parentId">
          <x-select-tree
            v-model="params.parentId"
            :options="menuTreeOptions"
            :placeholder="$t('auth.menu.root')"
            :defaultProps="defaultMenuProps"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('auth.menu.type')" prop="menuType">
          <x-radio-group :list-data="dictOptions['upms_menu.menu_type']" v-model="params.menuType"></x-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="`${getMenuTypeName(dictOptions['upms_menu.menu_type'], params.menuType)}名称`"
          prop="menuName"
        >
          <el-input v-model="params.menuName" :placeholder="$t('auth.menu.inputPlaceholder')" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="`${getMenuTypeName(dictOptions['upms_menu.menu_type'], params.menuType)}名称(英文)`"
          prop="menuNameEn"
        >
          <el-input v-model="params.menuNameEn" :placeholder="$t('auth.menu.inputPlaceholder')" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('auth.menu.path')" prop="router" v-if="params.menuType !== '3'">
          <el-input v-model="params.router" :placeholder="$t('auth.menu.inputPlaceholder')" clearable></el-input>
        </el-form-item>
      </el-col>
      <!-- <el-col :span="12">
        <el-form-item :label="'组件路径'" prop="component" v-if="params.menuType !== '3'">
          <el-input v-model="params.component" :placeholder="'请输入'"></el-input>
        </el-form-item>
      </el-col> -->
      <!-- <el-col :span="12">
        <el-form-item :label="'权限字符'" prop="perms">
          <el-input v-model="params.perms" :placeholder="'请输入'"></el-input>
        </el-form-item>
      </el-col> -->
      <el-col :span="12">
        <el-form-item :label="$t('auth.menu.icon')" prop="icon">
          <icon-select v-model="params.icon" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('auth.menu.sort')" prop="sort">
          <el-input-number size="small" v-model="params.sort" controls-position="right" :min="1"></el-input-number>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('auth.menu.state')" prop="state">
          <template #label>
            <span>
              {{ $t('auth.menu.state') }}
              <el-tooltip :content="$t('auth.menu.routerTips')" placement="top">
                <em class="el-icon-question" />
              </el-tooltip>
            </span>
          </template>
          <x-radio-group :list-data="dictOptions['system.state']" v-model="params.state"></x-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('auth.menu.outLink')" prop="isFrame">
          <template #label>
            {{ $t('auth.menu.outLink') }}
            <el-tooltip :content="$t('auth.menu.linkTips')" placement="top">
              <em class="el-icon-question" />
            </el-tooltip>
          </template>
          <x-radio-group :list-data="isFrameOptions" v-model="params.isFrame"></x-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('auth.menu.showState')" prop="isVisible">
          <template #label>
            <span>
              {{ $t('auth.menu.showState') }}
              <el-tooltip :content="$t('auth.menu.showStateTips')" placement="top">
                <em class="el-icon-question" />
              </el-tooltip>
            </span>
          </template>
          <x-radio-group :list-data="visibleOptions" v-model="params.isVisible"></x-radio-group>
        </el-form-item>
      </el-col>
      <!-- <el-col :span="12" /> -->
      <el-col :span="24" style="text-align: left" v-if="isShowFooter">
        <!-- <el-button v-if="!params.id" @click="handleClose"> {{ $t('common.cancel') }} </el-button> -->
        <el-button
          type="primary"
          v-hasPermi="['upms:menu:update']"
          @click="
            loading = true
            handleSubmit()
          "
          :loading="loading"
        >
          {{ $t('common.save') }}
        </el-button>
        <el-button v-hasPermi="['upms:menu:delete']" v-if="params?.id" type="danger" @click="handleDeleteMenu">
          {{ $t('common.delete') }}
        </el-button>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
  import { selectDictLabel, cloneDeep, omit, throttle } from '@package/utils'
  import IconSelect from '@/components/icon-select/iconSelect.vue'
  import { visibleOptions, isFrameOptions } from '../config/menuConfig.js'
  import { EnumApiCode } from '../../../../../../globalEnum'
  import { apiPostAddMenu, apiPostEditMenu, apiDeleteMenu } from '../api'

  export default {
    components: { IconSelect },
    props: {
      menuTreeData: {
        type: Array,
        default: () => []
      },
      defaultMenuProps: {
        type: Object,
        default: () => ({})
      },
      clientId: {
        type: String,
        default: ''
      },
      menuInfo: {
        type: Object,
        default: () => ({})
      },
      dictOptions: {
        type: Object,
        default: () => ({})
      },
      isShowFooter: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        title: this.$t('auth.menu.addMens'),
        isVisible: false,
        visibleOptions,
        isFrameOptions,
        loading: false,
        params: {
          parentId: '',
          menuName: '',
          menuNameEn: '',
          router: '',
          menuType: '1',
          perms: '',
          icon: '',
          sort: 1,
          state: '1',
          isFrame: '0',
          isVisible: '1',
          clientId: ''
        },
        rules: {
          parentId: [{ required: true, message: this.$t('auth.menu.prePlaceholder'), trigger: 'blur' }],
          menuName: [
            { required: true, message: this.$t('auth.menu.namePlaceholder'), trigger: 'blur' },
            { min: 1, max: 50, message: this.$t('auth.menu.lengthPlaceholder'), trigger: 'blur' }
          ],
          menuNameEn: [
            { required: true, message: this.$t('auth.menu.nameEnPlaceholder'), trigger: 'blur' },
            { min: 1, max: 50, message: this.$t('auth.menu.lengthPlaceholder'), trigger: 'blur' }
          ],
          menuType: [{ required: true, message: this.$t('auth.menu.typePlaceholder'), trigger: 'blur' }],
          isVisible: [{ required: true, message: this.$t('auth.menu.showStatePlaceholder'), trigger: 'blur' }],
          sort: [{ required: true, message: this.$t('auth.menu.sortPlaceholder'), trigger: 'blur' }],
          state: [{ required: true, message: this.$t('auth.menu.statePlaceholder'), trigger: 'blur' }],
          router: [{ required: true, message: this.$t('auth.menu.pathPlaceholder'), trigger: 'blur' }]
        },
        menuTreeOptions: []
      }
    },
    computed: {
      listUrl() {
        return this.menuBtnPageListUrl
      },
      menuTypeOptions() {
        const reusut = this.dictOptions['upms_menu.menu_type']?.filter((v) => `${v.value}` !== '3') ?? ''
        return reusut
      }
    },
    watch: {
      'menuTreeData.length': {
        handler(newVal) {
          if (this.menuTreeData?.length) {
            this.menuTreeOptions = [
              { menuName: this.$t('auth.menu.root'), id: '0', children: cloneDeep(this.menuTreeData) }
            ]
          }
        },
        deep: true,
        immediate: true
      },
      menuInfo: {
        handler(newVal) {
          this.$nextTick(() => {
            this.params = Object.assign(this.params, cloneDeep(newVal))
            this.params.state += ''
            this.params.isFrame += ''
            this.params.isVisible += ''
            this.params.menuType += ''
          })
        },
        deep: true,
        immediate: true
      }
    },
    methods: {
      getMenuTypeName(optison, value) {
        return selectDictLabel(optison, value)
      },
      handleSubmit: throttle(function () {
        return new Promise((resolve, reject) => {
          this.$refs.params.validate(async (valid) => {
            if (valid) {
              const param = {
                ...this.params,
                clientId: this.clientId
              }
              try {
                this.loading = true
                const { code, msg } = this.params.id ? await apiPostEditMenu(param) : await apiPostAddMenu(param)
                this.loading = false
                if (code === EnumApiCode.Success) {
                  this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                  // this.params = omit(this.params, 'id')

                  this.$emit('handleSuccess')
                  resolve()
                } else {
                  this.$message.error(msg)
                  reject()
                }
              } catch (e) {
                this.loading = false
                reject()
              }
            } else {
              return false
            }
          })
        })
      }, 1000),
      handleClose() {
        this.$refs.params.resetFields()
        this.params = omit(this.params, 'id')
        this.$emit('handleClose')
        // this.isVisible = false
      },
      handleDeleteMenu: throttle(function () {
        this.$confirm(this.$t('auth.menu.deletePrmo'), this.$t('auth.menu.prompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        })
          .then((confirm) => {
            apiDeleteMenu(this.params.id).then(({ code, msg }) => {
              if (code === EnumApiCode.Success) {
                // this.$refs['params'].resetFields()
                this.$message.success(this.$t('auth.role.successTips'))
                this.$emit('handleDelSuccess')
                // this.isVisible = false
              } else {
                this.$message.error(msg)
              }
            })
          })
          .catch((cancel) => {})
      }, 1000)
    }
  }
</script>
